#include "stringlib.h"
#include <windows.h>

#include <stdio.h> // for UT();

//////////////////////////////////////////////////////////////////////////

namespace stringlib
{

char* StrCpyAlloc(const char *szSource)
{
	char *szNew = new char [strlen(szSource)+1];
	strcpy(szNew, szSource);
	return szNew;
} 

wchar_t * AnsiToUnicode(const char *szANSI, int nMinLen)
{
	wchar_t *szUNI;

	// First find out how many wide chars we need
	int nLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szANSI, -1, NULL, 0);

	if (nLen == 0)
		return NULL;							// Unable to convert (unlikely)

	// Allocate our buffer (must be at least nMinLen chars)
	if (nMinLen > nLen)
		szUNI = new wchar_t[nMinLen];
	else
		szUNI = new wchar_t[nLen];

	// Do the conversion proper
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szANSI, -1, szUNI, nLen);

	return szUNI;

} 

char * UnicodeToAnsi(const wchar_t *szUNI, int nMinLen)
{
	char *szANSI;

	// First find out how many wide chars we need
	int nLen = WideCharToMultiByte(CP_ACP, 0, szUNI, -1, NULL, 0, NULL, NULL);

	if (nLen == 0)
		return NULL;							// Unable to convert (unlikely)

	// Allocate our buffer (must be at least nMinLen chars)
	if (nMinLen > nLen)
		szANSI = new char[nMinLen];
	else
		szANSI = new char[nLen];

	// Do the conversion proper
	WideCharToMultiByte(CP_ACP, 0, szUNI, -1, szANSI, nLen, NULL, NULL);

	return szANSI;

} 

char* StrReplace( const char *source, const char *oldValue, const char *newValue )
{
	char *ret;
	int i, count = 0;
	size_t newlen = strlen(newValue);
	size_t oldlen = strlen(oldValue);

	for (i = 0; source[i] != '\0'; i++) {
		if (strstr(&source[i], oldValue) == &source[i]) {
			count++;
			i += oldlen - 1;
		}
	}

	ret = new char[i + count * (newlen - oldlen) + 1];

	if (ret == NULL)
		exit(EXIT_FAILURE);

	i = 0;
	while (*source) {
		if (strstr(source, oldValue) == source) {
			strcpy(&ret[i], newValue);
			i += newlen;
			source += oldlen;
		} else
			ret[i++] = *source++;
	}
	ret[i] = '\0';

	return ret;
}

void UT()
{
	char* clone = StrCpyAlloc("Test StrCpyAlloc");
	printf("TEST StrCpyAlloc, %s\n", clone);
	delete clone;

	wchar_t* w_clone = AnsiToUnicode("Test Ansi <--> Unicode", 100);
	// print wchar char
	//         %ls   %s
	printf("TEST AnsiToUnicode, %ls\n", w_clone);

	clone = UnicodeToAnsi(w_clone, 100);
	printf("TEST UnicodeToAnsi, %s\n", clone);
	
	delete w_clone;
	delete clone;

	char mystr[] = "##this is##a examp#le";
	char *newstr = NULL;

	puts(mystr);
	newstr = StrReplace(mystr, "##", "****");
	printf("%s\n", newstr);

	delete newstr;
}



} // namespace stringlib